package org.hales.controller;

import io.swagger.annotations.ApiOperation;
import org.hales.manager.RequestManager;
import org.hales.util.GraphicUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

@RestController
/**
 * @author 陈建康
 */
public class UserController {

    @GetMapping("createImageCode.do")
    @ApiOperation("生成图片验证码")
    public void createImageCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        RequestManager.currentSession(); // 创建session

        // 设置验证码图片 cookie
        Cookie cookie = new Cookie("JSESSIONID", RequestManager.currentSession().getId());
        cookie.setPath(RequestManager.currentContextPath());
        cookie.setSecure(false);
        cookie.setHttpOnly(true);
        response.addCookie(cookie);

        // 设置响应头
        response.setContentType("image/jpeg"); // 设置返回类型为图片
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expire", 0);



        final OutputStream output = response.getOutputStream(); // 获取输出流
        final int width = 120;
        final int height = 30;
        final String imgType = "jpeg";

        // 创建验证码图片并返回图片上的字符串
        String code = GraphicUtil.createImageCode(width, height, imgType, output);
        System.out.println(code);
        // 在session中存储校验码
        RequestManager.setCheckCode(code);

        output.flush(); // 刷新输出流
        output.close(); // 关闭输出流（可以不写，Spring 容器会帮忙关闭）
    }
}
